﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.Repository
{
    public class BaseRepository<T> : IRepository<T> where T : class, new()
    {
        protected readonly EFCoreContext context;
        public BaseRepository(EFCoreContext context)
        {
            this.context = context;
        }

        public async Task<int> AddAsync(T entity)
        {
            await context.Set<T>().AddAsync(entity);
            return context.SaveChanges();
        }

        public async Task<int> Delete(int id)
        {
            var arr = await context.Set<T>().FindAsync(id);
            context.Remove(arr);
            return context.SaveChanges();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await context.Set<T>().ToListAsync();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await context.Set<T>().Where(expre).ToListAsync();
        }

        public async Task<T> GetModelAsync(int id)
        {
            return await context.Set<T>().FindAsync(id);
        }

        public async Task<int> Update(T entity)
        {
            context.Update(entity);
            return await context.SaveChangesAsync();
        }
    }
}
